package com.qf.shiro;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qf.mapper.DtsAdminMapper;
import com.qf.pojo.DtsAdmin;
import com.qf.service.DtsAdminService;
import com.qf.service.PermissionService;
import com.qf.service.RoleService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;


public class AdminAuthorizingRealm extends AuthorizingRealm {


    @Autowired
    private DtsAdminService dtsAdminService;

    @Autowired
    private DtsAdminMapper dtsAdminMapper;

    @Autowired
    private RoleService roleService;

    @Autowired
    private PermissionService permissionService;


    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //获取用户对象
        DtsAdmin dtsAdmin = (DtsAdmin) principals.getPrimaryPrincipal();
        //获取用户的角色数组
        Integer[] roleIds = dtsAdmin.getRoleIds();
        //根据角色数组获取用户对应的用户名称集合
        Set<String> roles = roleService.queryByRoleIds(roleIds);
        //根据用户的角色数组查询对应的权限集合
        Set<String> permissions = permissionService.queryByRoleIds(roleIds);

        SimpleAuthorizationInfo Info = new SimpleAuthorizationInfo();

        //将用户拥有的角色放入shiro框架中
        Info.setRoles(roles);
        //将用户拥有的权限放入shiro框架中
        Info.setStringPermissions(permissions);

        return Info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken)token;
        String username = usernamePasswordToken.getUsername();
        String password = String.valueOf(usernamePasswordToken.getPassword());

        DtsAdmin dtsAdmin = dtsAdminMapper.selectOne(new LambdaQueryWrapper<DtsAdmin>()
                .eq(DtsAdmin::getUsername, username)
                .eq(DtsAdmin::getDeleted, false));


/*        List<DtsAdmin> dtsAdmins = dtsAdminService.queryAdminByUsername(username);
        DtsAdmin dtsAdmin = dtsAdmins.get(0);*/


        if (null == dtsAdmin){
            throw new UnknownAccountException();
        }
        if (!dtsAdmin.getPassword().equals(password)) {
            //密码不正确
            throw new IncorrectCredentialsException();
        }

        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(dtsAdmin,password,this.getName());
        return simpleAuthenticationInfo;
    }


}
